export function timeArr2DateObj(timeArr) {
	var obj = JSON.parse(JSON.stringify(timeArr))
	obj[1]--
	return new Date(...obj)
}

export function timeArr2HumanStr(timeArr) {
	try {
		return timeArr2DateObj(timeArr).toLocaleString()
	} catch (error) {
		return 'error'
	}
}

export function getRelativeHumanTimeFromTimeArr(timeArr) {
	let ms = new Date() - timeArr2DateObj(timeArr)

	let s = Math.floor(ms / 1000)
	if (s < 60) {
		return `${s}秒前`
	}

	let m = Math.floor(ms / 1000 / 60)
	if (m < 60) {
		return `${m}分钟前`
	}

	let h = Math.floor(ms / 1000 / 60 / 60)
	if (h < 24) {
		return `${h}小时前`
	}

	let d = Math.floor(ms / 1000 / 60 / 60 / 24)
	if (d < 30) {
		return `${d}天前`
	}

	let M = Math.floor(ms / 1000 / 60 / 60 / 24 / 30)
	if (M < 12) {
		return `${M}个月前`
	}

	let y = Math.floor(ms / 1000 / 60 / 60 / 24 / 30 / 12)
	return `${y}年前`
}

export function gotoUrl(url) {
	console.log('gotoUrl:', url)
	uni.navigateTo({
		url: url,
	})
}

export function goBack() {
	uni.navigateBack({
		fail() {
			uni.switchTab({
				url: '/pages/indexNew/indexNew'
			})
		}
	})
}

export const addHistory = (title, img) => {
	let hist = []
	try {
		hist = JSON.parse(uni.getStorageSync('browsing_history'))
	} catch (e) {}

	let pageStack = getCurrentPages()
	let url = pageStack[pageStack.length - 1].$page.fullPath

	if (url.includes('/pages/booksPages/booksPages')) {
		url = decodeURIComponent(url)
	}

	let histAdd = {
		title: title,
		url: url, // current page href
		img: img,
		time: Date.now()
	}

	console.log('adding history:', histAdd)
	hist.push(histAdd)

	// limit size to 100 items or 100KB
	while (hist.length > 100 || JSON.stringify(hist).length > 1024 * 100) {
		hist.splice(0, 1)
	}

	uni.setStorageSync('browsing_history', JSON.stringify(hist))
}

export function UploadImg() {
	// 更换头像函数
	return new Promise((resolve, reject) => {
		var _that = this
		uni.chooseImage({
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				var that = this

				//上传一个图片，并返回地址
				uni.uploadFile({
					url: _that.$baseUrl + '/common/upload',
					filePath: tempFilePaths[0],
					name: 'files',
					count: 1,
					formData: {
						count: 1, // 设置 count 参数为 0,
					},
					success: (uploadFileRes) => {
						console.log("uploadFileRes.data==>" + uploadFileRes
							.data);
						resolve(uploadFileRes.data)
					}
				});
			}
		});
	})
}